<?php
/*
 * @Description    : 
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2020-02-08 15:01:43
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-05-15 17:36:18
 */

declare(strict_types=1);

namespace App\Controller;

use App\Common\RedisCache;
use App\Constants\Status;
use App\Exception\ApiException;
use Qianlong\Validate\Validate;

class PlatformController extends AbstractController
{
  public function ak()
  {
    $valitor = new Validate();
    $valitor->addColumn('ak_id')->required();
    if ($valitor && !$this->validate($valitor)) {
      throw new ApiException(Status::CODE_BAD_REQUEST, $valitor->getError()->__toString());
    }
    unset($valitor);
    $param = $this->request->all();
    $userInfo = $this->dataResource->getUserInfo();
    $redisCache = new RedisCache;
    $akInfo = $redisCache->getAk($param['ak_id'], (int)$userInfo['uid']);
    if ($akInfo['status'] != 1) {
      throw new ApiException(-1,'AK凭证未启用');
    }
    if (isset($akInfo['is_ip_limit']) && $akInfo['is_ip_limit'] == 1) {
      $remoteIp = $this->dataResource->getClientIp($this->request);
      $sysSetting = $redisCache->getSysSetting();
      $allIp = $sysSetting['server_ip'] . ',' . $akInfo['limit_server_ip'];
      $server_ip = explode(',', $allIp);
      $is_local = filter_var($remoteIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
      if (!in_array($remoteIp, $server_ip) && $is_local != false) {
        throw new ApiException(-1, 'IP不在可信范围内 '. $remoteIp);
      }
    }
    unset($akInfo['create_time'], $akInfo['uid'], $akInfo['username'], $akInfo['id']);
    return $this->response->json(Status::CODE_OK, 'success', $akInfo);
  }
}
